package com.cn.intelligence.service.impl;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.intelligence.mapper.TbCartMapper;
import com.cn.intelligence.mapper.TbItemMapper;
import com.cn.intelligence.mapper.TbMUserMapper;
import com.cn.intelligence.mapper.TbOrderMapper;
import com.cn.intelligence.mapper.TbSendProductMapper;
import com.cn.intelligence.mapper.TbUserMapper;
import com.cn.intelligence.mapper.WuliuMapper;
import com.cn.intelligence.pojo.EUDataGridResult;
import com.cn.intelligence.pojo.TaotaoResult;
import com.cn.intelligence.pojo.TbCart;
import com.cn.intelligence.pojo.TbCartExample;
import com.cn.intelligence.pojo.TbItem;
import com.cn.intelligence.pojo.TbMUser;
import com.cn.intelligence.pojo.TbOrder;
import com.cn.intelligence.pojo.TbOrderExample;
import com.cn.intelligence.pojo.TbSendProduct;
import com.cn.intelligence.pojo.TbSendProductExample;
import com.cn.intelligence.pojo.TbUser;
import com.cn.intelligence.pojo.TbUserExample;
import com.cn.intelligence.pojo.TemplateValue;
import com.cn.intelligence.pojo.Wuliu;
import com.cn.intelligence.pojo.WuliuExample;
import com.cn.intelligence.service.CusUserService;
import com.cn.intelligence.util.IDUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cn.intelligence.util.*;
@Service
public class CusUserServiceImpl implements CusUserService {

	@Autowired
	public TbUserMapper tbUserMapper;
	@Autowired
	public TbOrderMapper tbOrderMapper;
	@Autowired
	public TbSendProductMapper tbSendProductMapper;
	@Autowired
	public TbMUserMapper tbMUserMapper;
	@Autowired
	public TbCartMapper tbCartMapper;
	@Autowired
	private WuliuMapper wuliuMapper;
	@Autowired
	public TbItemMapper tbItemMapper;

	/**
	 * 获取系统用户
	 */
	@Override
	public EUDataGridResult getCusUserList(Integer page, Integer rows) {
		TbUserExample TbUserExample = new TbUserExample();
		// 分页查询
		PageHelper.startPage(page, rows);
		List<TbUser> TbUserList = tbUserMapper.selectByExample(TbUserExample);
		// 获取总数
		PageInfo<TbUser> pageInfo = new PageInfo<TbUser>(TbUserList);
		// 实现返回值设定
		EUDataGridResult euDataGridResult = new EUDataGridResult();
		euDataGridResult.setRows(TbUserList);
		euDataGridResult.setTotal(pageInfo.getTotal());
		return euDataGridResult;

	}

	/**
	 * 添加修改用户信息
	 */
	@Override
	public TaotaoResult insertTbUser(TbUser TbUser) {
		TbUserExample TbUserExample = new TbUserExample();
		TbUserExample.Criteria criteria = TbUserExample.createCriteria();
		int value = 0;
		if(TbUser.getId() == null || "".equals(TbUser.getId())){
			long ids = IDUtils.genItemId();
			TbUser.setId(ids);
			TbUser.setCreated(new Date());
			TbUser.setUpdated(new Date());
			value = tbUserMapper.insert(TbUser);
		}else{
			criteria.andIdEqualTo(TbUser.getId());
			TbUser exitTbUser = tbUserMapper.selectByPrimaryKey(TbUser.getId());	
			if(exitTbUser != null){
				TbUser.setUpdated(new Date());
				value = tbUserMapper.updateByExampleSelective(TbUser, TbUserExample);	
			}else{
				return TaotaoResult.fail();
			}
		}
		if(value == 0){
			return TaotaoResult.ok();
		}else{
			return TaotaoResult.fail();
		}
	
	}

	@Override
	public TaotaoResult deleteUser(Long[] ids) {
		TbUserExample TbUserExample = new TbUserExample();
		TbUserExample.Criteria criteria = TbUserExample.createCriteria();
		criteria.andIdIn(Arrays.asList(ids));
		int value = tbUserMapper.deleteByExample(TbUserExample);	
		if(value == ids.length){
			return TaotaoResult.ok();
		}else{
			return TaotaoResult.fail();
		}
	}

	@Override
	public EUDataGridResult getCusUser(String username, int page, int rows) {
		TbUserExample TbUserExample = new TbUserExample();
		TbUserExample.Criteria criteria = TbUserExample.createCriteria();
		criteria.andNicknameLike(username);
		// 分页查询
		PageHelper.startPage(page, rows);
		List<TbUser> TbUserList = tbUserMapper.selectByExample(TbUserExample);
		// 获取总数
		PageInfo<TbUser> pageInfo = new PageInfo<TbUser>(TbUserList);
		// 实现返回值设定
		EUDataGridResult euDataGridResult = new EUDataGridResult();
		euDataGridResult.setRows(TbUserList);
		euDataGridResult.setTotal(pageInfo.getTotal());
		return euDataGridResult;

	}
	/**
	 * 发货
	 */
	@Override
	public TaotaoResult sendProduct(final TbOrder tbOrder) {
		// 查询改订单是否真实有效
		TbOrderExample orderExample = new TbOrderExample();
		TbOrderExample.Criteria criteria = orderExample.createCriteria();
		criteria.andOrderIdEqualTo(tbOrder.getOrderId());
		 List<TbOrder> orderlist = tbOrderMapper.selectByExample(orderExample);
		 if(orderlist ==null || orderlist.size()<0){
			return  TaotaoResult.ok("该订单不存在，发货失败");
		 }else{
			 tbOrder.setUpdateTime(new Date());
			 tbOrder.setConsignTime(new Date());
			 tbOrder.setStatus(4);
			 
	/*		 WuliuExample wuliuExample = new WuliuExample();
			 WuliuExample.Criteria criteria3 = wuliuExample.createCriteria();
			 criteria3.andNameEqualTo(tbOrder.getShippingName());
			 List<Wuliu> Wuliu= wuliuMapper.selectByExample(wuliuExample);
			 tbOrder.setShippingName(Wuliu.get(0).getId().toString());*/
			 int value = tbOrderMapper.updateByExampleSelective(tbOrder, orderExample);
			 
			 try {
				 System.out.println("-----------------------");
				 TbOrder tt2 = tbOrderMapper.selectByPrimaryKey(tbOrder.getOrderId());
				 System.out.println(tt2);
				 String[]  prepay_id = tbOrderMapper.selectByPrimaryKey(tt2.getOrderId()).getPackageInfo().split("=");
				 System.out.println(prepay_id);
				 
					Wuliu wuliu = wuliuMapper.selectByPrimaryKey(Long.parseLong(tt2.getShippingName()));
				 
				TemplateValue list1 = new TemplateValue();
				list1.setValue(wuliu.getName());
				list1.setColor("#173177");
				TemplateValue list2 = new TemplateValue();
				list2.setValue(tt2.getShippingCode());
				list2.setColor("#173177");
				 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  				
				TemplateValue list3 = new TemplateValue();
				list3.setValue(dateFormat.format(tt2.getUpdateTime()));
				list3.setColor("#173177");
				TemplateValue list4 = new TemplateValue();
				list4.setValue(tt2.getOrderId());
				list4.setColor("#173177");
				 
		        Map<String, Object> map1 = new HashMap<String, Object>();
		        map1.put("keyword1", list1);
		        map1.put("keyword2", list2);
		        map1.put("keyword3", list3);
		        map1.put("keyword4", list4);

				 if (prepay_id.length == 2) {
					 SendWxTemplateMessage.sender(tbUserMapper.selectByPrimaryKey(tbOrderMapper.selectByPrimaryKey(tbOrder.getOrderId()).getUserId()).getOpenid(),prepay_id[1],map1);
				 }else{
					 return TaotaoResult.ok("该订单prepay_id不存在，发货失败");
				 }
				 
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 if(value==0){
				 return  TaotaoResult.ok("该订单不存在，发货失败");
			 }else{
				 
			 }
			 return TaotaoResult.ok(tbOrder);
		 }
		
	}
	
	/**
	 * 分配发货
	 */
	@Override
	public TaotaoResult addProductSender(String orderIds, String senders, String sendRemark) throws Exception {
		
		System.out.println(orderIds);
		System.out.println(orderIds.indexOf("|"));
		if(orderIds !=null && !"".equals(orderIds)){
			 String  orderlist[] = orderIds.split(",");
			for (int i = 0; i < orderlist.length; i++) {
				// 添加发货者
				TbSendProduct tbSendProduct = new TbSendProduct();
				long ids = IDUtils.genItemId();
				tbSendProduct.setId(ids);
				tbSendProduct.setOrderId(Long.parseLong(orderlist[i]));
				tbSendProduct.setUid(Long.parseLong(senders));
				tbSendProduct.setRemark(sendRemark);
				tbSendProduct.setCreated(new Date());
				tbSendProduct.setUpdated(new Date());
				int flag = tbSendProductMapper.insertSelective(tbSendProduct);
				if(flag==0){
					throw new Exception();
				}
				// 修改订单状态状态
				TbOrderExample tbOrderExample = new TbOrderExample();
				TbOrderExample.Criteria criteriaItem = tbOrderExample.createCriteria();
				criteriaItem.andOrderIdEqualTo(orderlist[i]);
				TbOrder tborder = new TbOrder();
				// 修建订单状态为已分配发货员
				tborder.setStatus(9);
				tborder.setUpdateTime(new Date());
				int flag2 = tbOrderMapper.updateByExampleSelective(tborder, tbOrderExample);
				if(flag2==0){
					throw new Exception();
				}
			}
			
		}
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult findProductSender(String orderId) {
		Map<String,Object> result = new HashMap<String,Object>();
		TbOrder tbOrder =tbOrderMapper.selectByPrimaryKey(orderId);
		TbSendProductExample sendExample = new TbSendProductExample();
		TbSendProductExample.Criteria criteria = sendExample.createCriteria();
		criteria.andOrderIdEqualTo(Long.parseLong(orderId));
		List<TbSendProduct>  senderlist = tbSendProductMapper.selectByExample(sendExample);
		if(senderlist!=null && senderlist.size()>0){
			
			TbMUser tbmuser = tbMUserMapper.selectByPrimaryKey(senderlist.get(0).getUid());
			// 发货员信息
			result.put("senderId", tbmuser.getId());
			result.put("senderName", tbmuser.getUsername());
			// 发货员信息
			result.put("senderRemark", tbOrder.getSendRemark());
			// 发货员信息
			result.put("remark", senderlist.get(0).getRemark());
			//物流信息
			result.put("shippingCode", tbOrder.getShippingCode());
			result.put("shippingName", tbOrder.getShippingName());
			
		}
		// TODO Auto-generated method stub
		return TaotaoResult.ok(result);
	}

	@Override
	public TaotaoResult findProdByCart(String cartId){
		// 查询该订单购物车信息
		TbCart tbcart = tbCartMapper.selectByPrimaryKey(Long.parseLong(cartId));
		// 查询商品
		TbItem bitem =tbItemMapper.selectByPrimaryKey(tbcart.getPid());
		// 返回结果
		return TaotaoResult.ok(bitem);
		
	}

	@Override
	public TaotaoResult findProdByCarts(String cartId){
		String[] carts = cartId.split(",");
		List<Long> lcartId = new ArrayList<Long>();
		for (String string : carts) {
			lcartId.add(Long.parseLong(string));
		}
		TbCartExample example = new TbCartExample();
		TbCartExample.Criteria criterira = example.createCriteria();
		criterira.andIdIn(lcartId);
		// 查询该订单购物车信息
		List<TbCart> tbcartlist = tbCartMapper.selectByExample(example);
		List<TbItem> resultTbItem =new ArrayList<TbItem>(); 
		int indexy = 0;
		for (TbCart tbCart2 : tbcartlist) {
			// 查询商品
			TbItem   bitem = tbItemMapper.selectByPrimaryKey(tbCart2.getPid());
			try {
				bitem = bitem.clone();
			} catch (CloneNotSupportedException ex) {
				ex.printStackTrace();
			}

			bitem.setParams(tbCart2.getParams());//这一步会改变所有已经添加到resultbitem中的bitem

			resultTbItem.add(bitem);
			resultTbItem.get(indexy).setParams(tbCart2.getParams());
			System.out.println(tbCart2.getParams());
			System.out.println(resultTbItem);
			System.out.println("----------------");
			indexy++;
		}

		// 返回结果
		return TaotaoResult.ok(resultTbItem);
		
	}

}
